package com.xiao.springcloud.controller;

import com.xiao.springcloud.entity.Payment;
import com.xiao.springcloud.entity.Result;
import com.xiao.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    PaymentService paymentService;

    @Value("${server.port}")
    String serverPort;

    @Resource
    DiscoveryClient discoveryClient;

    @PostMapping("/create")
    public Result create(@RequestBody Payment payment){
        Result result = null;
        try{
            int num = paymentService.create(payment);
            if(num>0){
                result=new Result(true,"插入数据成功");
                log.info("******插入"+payment+",port: " + serverPort + "成功******");
            }else{
                result=new Result(false,"插入数据失败");
                log.info("******插入"+payment+"失败******");
            }
        }catch (Exception e){
            result=new Result(false,"插入数据失败");
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/get/{id}")
    public Result getPaymentById(@PathVariable Long id){
        Result result = null;
        try{
            Payment payment = paymentService.selectPaymentById(id);
            if(payment != null){
                result=new Result(true,"获取数据成功",payment);
                log.info("******根据id:"+id+"获取"+payment+",port: " + serverPort + "成功******");
            }else{
                result=new Result(false,"获取数据失败");
                log.info("******根据id:"+id+"获取数据失败******");
            }
        }catch (Exception e){
            result=new Result(false,"获取数据失败");
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("/getDiscover")
    public Object discover(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("******service :" + service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-PAYMENT");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() +"\t"+instance.getHost() + "\t" +instance.getPort()
                    +"\t" +instance.getUri());
        }

        return this.discoveryClient;
    }
}
